import {
	BASEURL,
	TIMEOUT
} from '../../constant/index.js'
import {
	removeParam,
	parseQuery
} from '@/utils/index.js'

const registerHttp = (vm) => {
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = BASEURL
		config.timeout = TIMEOUT
		config.custom = {
			loading: true,
			loadingTitle: '加载中',
			mask: true
		}
		return config
	})

	// 请求拦截器
	uni.$u.http.interceptors.request.use((config) => {
		// 设置token
		if (vm.$store.state.login.token) {
			vm.$store.state.login.userInfo.is_sale ? config.header.Admintoken = vm.$store.state.login
				.token : config.header.Apitoken = vm.$store.state.login.token
		}
		if (config.custom.noToken) {
			vm.$store.state.login.userInfo.is_sale ? delete config.header.Admintoken : delete config.header
				.Apitoken
		}
		if (config.custom.noBaseUrl) {
			config.baseURL = ''
		}

		if (config.custom.loading) uni.showLoading({
			title: config.custom.loadingTitle,
			mask: config.custom.mask
		})

		return config
	}, (err) => {
		return err
	})

	//响应拦截器
	uni.$u.http.interceptors.response.use(({
		data,
		config
	}) => {
		// 用户token过期
		if (data.code === 401) {
			if (data.msg == '账号已被禁用') {
				const divElement = document.createElement('div');
				divElement.innerHTML =
					`<div style='position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgb(255, 255, 255); color: #383838; z-index: 99999; text-align: center; padding-top: 20%;'>找不到该文章了o(╥﹏╥)o</div>`;
				document.body.appendChild(divElement);
				return uni.hideLoading()
			}
			vm.$showToast('自动登录中...')
			setTimeout(() => {
				if (vm.$store.state.login.system === 'h5') {
					const {
						code,
						appid,
						key
					} = parseQuery()
					if (key == 'pc') return vm.$showToast('token已失效!')
					// 境外跳转回境内授权
					if (vm.$store.state.login.redirect_uri) {
						window.location.href = `${vm.$store.state.login.redirect_uri}/user/#/?appid=${appid}`
					} else {
						// 境内
						// 清除token
						if (Object.keys(vm.$store.state.login.userInfo).length) {
							vm.$store.dispatch('login/loginOut')
							let http = `${window.location.href}`
							http = removeParam("state", http)
							http = removeParam("code", http)
							window.location.href =
								`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(http.replace("#", "virtually"))}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
						}
					}
				} else {

				}
			}, 0)
			return uni.hideLoading()
		}
		if (data.code !== 200 && data.code !== 401) {
			uni.hideLoading()
			vm.$showToast(data.msg)
			return Promise.reject(data)
		}
		if (data.code === 200) uni.hideLoading()
		return data
	}, (err) => {
		vm.$showToast('网络异常，请稍后操作')
		return Promise.reject(err)
	})
}

export default registerHttp